import { Response } from 'express'
import { v4 as uuid } from 'uuid'
import {parseToken} from "../utils/jwt";
import {IPromiseCommonResponse, ISqlInsert, tokenParams} from "../../global";
import {commonResponse} from "../utils/commonResponse";
import {flowAddDao, flowDelDao, flowListDao, flowViewDao, IFlow} from "../dao/flowDao";
import dayjs from "dayjs";
import FileMethod from "../utils/fileMethod";

export const flowAddService = async (res: Response, path: string, name: string, describe: string, token: string) => {
    await commonResponse<IPromiseCommonResponse<ISqlInsert>, ISqlInsert>(res, async () => {
        const params = parseToken(token) as tokenParams
        return Promise.resolve({ code: 200, data: await flowAddDao([uuid(), params.userUID, path, name, describe, dayjs().format('YYYY-MM-DD HH-mm-ss')])})
    })
}

export const flowListService = async (res: Response, token: string) => {
    await commonResponse<IPromiseCommonResponse<Array<IFlow>>, Array<IFlow>>(res, async () => {
        const params = parseToken(token) as tokenParams
        const list = await flowListDao([params.userUID])
        for (let i = 0; i < list.length; i++) {
            list[i].key = list[i].flowUID
        }
        return Promise.resolve({ code: 200, data: list })
    })
}

export const flowViewService = async (res: Response, flowUID: string) => {
    await commonResponse<IPromiseCommonResponse<IFlow>, IFlow>(res, async () => {
        return Promise.resolve({ code: 200, data: (await flowViewDao([flowUID]))[0]})
    })
}

export const flowDelService = async (res: Response, flowUID: string, path: string) => {
    await commonResponse<IPromiseCommonResponse<{ msg: string }>, { msg: string }>(res, async () => {
        await flowDelDao([flowUID])
        await FileMethod.fileDel(path)
        return Promise.resolve({ code: 200, data: { msg: '成功' } })
    })
}